package com.b2c.open.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.b2c.open.gateway.common.ResponseCode;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 三方应用权限过滤器
 * liuyu07
 */
public class ThirdAuthGatewayFilter implements GatewayFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(ThirdAuthGatewayFilter.class);
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("三方应用过滤器, 开始");
        //1、校验appId和token是否为空
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //在URL中获取appId和token
        String appKey = exchange.getRequest().getQueryParams().getFirst("appKey");
        String appId = exchange.getRequest().getQueryParams().getFirst("appId");
        if(StringUtils.isBlank(appKey) || StringUtils.isBlank(appId)){
            //从header中获取appId和token
            List<String> appIds = request.getHeaders().get("appId");
            List<String> appKeys = request.getHeaders().get("appKey");
            if(appIds == null || appIds.isEmpty()){
                JSONObject message = new JSONObject();
                message.put("code", ResponseCode.ERR_APP_ID_NULL.getCode());
                message.put("msg", ResponseCode.ERR_APP_ID_NULL.getMessage());
                logger.info("三方应用过滤器, 结束. message={}", message);
                return getVoidMono(response, message);
            }
            if(appKeys == null || appKeys.isEmpty()){
                JSONObject message = new JSONObject();
                message.put("code", ResponseCode.ERR_APP_TOKEN_NULL.getCode());
                message.put("msg", ResponseCode.ERR_APP_TOKEN_NULL.getMessage());
                logger.info("三方应用过滤器, 结束. message={}", message);
                return getVoidMono(response, message);
            }
            appKey = appKeys.get(0);
            appId = appIds.get(0);
        }
        String path = request.getPath().value();
        logger.info("三方应用过滤器参数：appId={}, path={}, appKey={}", appId, path, appKey);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return FilterOrder.THIRD_AUTH_FILTER_ORDER;
    }

    private Mono<Void> getVoidMono(ServerHttpResponse response, JSONObject message) {
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.OK);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        return response.writeWith(Mono.just(buffer));
    }
}
